package com.cn.medicalcare.customtool;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.*;
import java.util.function.Function;

public class JedisUtil {

    private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;

    public static final int CACHE_TIME = 12 * 60 * 60;

    private JedisUtil() {
    }

    private static JedisPool jedisPool;
    private static String host;
    private static int port;
    private static int maxtotal;
    private static int maxwaitmillis;

    /*读取jedis.properties配置文件*/
    static {
        ResourceBundle rb = ResourceBundle.getBundle("redis-config/jedis");
        host = rb.getString("host");
        port = Integer.parseInt(rb.getString("port"));
        maxtotal = Integer.parseInt(rb.getString("maxtotal"));
        maxwaitmillis = Integer.parseInt(rb.getString("maxwaitmillis"));
    }

    /*创建连接池*/
    static {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(maxtotal);
        jedisPoolConfig.setMaxWaitMillis(maxwaitmillis);
        jedisPool = new JedisPool(jedisPoolConfig, host, port);

//        setTimer();
    }

    /*获取jedis*/
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

    /**
     * Jedis 操作Redis
     *
     * @param func 函数式接口，用于实现Jedis的具体操作，推荐使用lamda
     * @param <R>  Jedis操作后的结果类型
     * @return Jedis操作后的结果
     */
    public static <R> R jedisDo(Function<Jedis, R> func) {
        Jedis jedis = null;
        R r = null;
        try {
            jedis = jedisPool.getResource();
            r = func.apply(jedis);
        } catch (Exception e) {
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return r;
    }

    /*关闭Jedis*/
    public static void close(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    /**
     * 删除所有匹配的key
     * 可用使用通配符
     *
     * @param pattern key的表达式
     */
    public synchronized static void deleteKeys(String pattern) {
        //列出所有匹配的key
        Jedis jedis = getJedis();
        Set<String> keySet = jedis.keys(pattern);
        if (keySet != null && keySet.size() > 0) {
            String keyArr[] = new String[keySet.size()];
            int i = 0;
            for (String keys : keySet) {
                keyArr[i] = keys;
                i++;
            }
            jedis.del(keyArr);
        }
        close(jedis);
    }

    private static void setTimer() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 1); //凌晨1点
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date date = calendar.getTime(); //第一次执行定时任务的时间
        //如果第一次执行定时任务的时间 小于当前的时间
        //此时要在 第一次执行定时任务的时间加一天，以便此任务在下个时间点执行。如果不加一天，任务会立即执行。
        if (date.before(new Date())) {
            date = addDay(date, 1);
        }
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                jedisDo(j -> j.flushDB());
            }
        };
        //安排指定的任务在指定的时间开始进行重复的固定延迟执行。
        timer.scheduleAtFixedRate(task, date, PERIOD_DAY);
    }

    private static Date addDay(Date date, int num) {
        Calendar startDT = Calendar.getInstance();
        startDT.setTime(date);
        startDT.add(Calendar.DAY_OF_MONTH, num);
        return startDT.getTime();
    }
}
